package com.bookdresser.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import android.graphics.drawable.Drawable;
import android.util.Xml;

import com.bookdresser.model.BookItem;

public class BooksDataDeal {

	public List<BookItem> getBooksData() {

		List<BookItem> list = new ArrayList<BookItem>();
		String path = SystemConstants.CACHE_BOOKS_DATA_XML_PATH;
		XmlPullParser xmlPull = Xml.newPullParser();

		int type = 0;
		try {
			InputStream in = new FileInputStream(path);
			xmlPull.setInput(in, "GBK");
		
			type = xmlPull.getEventType();

			while (type != XmlPullParser.END_DOCUMENT) {
				switch (type) {
				case XmlPullParser.START_DOCUMENT:
					// 数据初始化化处理Perno nn = new Perno();
					break;
				case XmlPullParser.START_TAG:// 标签开始
					String tagName = xmlPull.getName();
					if (tagName.equalsIgnoreCase("book")) {
						BookItem bookItem = new BookItem();
						//String id = xmlPull.getAttributeValue(null, "id");// 通过属性名来获取属性值
						String name = xmlPull.getAttributeValue(null, "name");
						String imgPath = xmlPull.getAttributeValue(null, "uri");
						int state = Integer.parseInt(xmlPull.getAttributeValue(
								null, "state"));// 通过属性名来获取属性值
						String publishingHouse = xmlPull.getAttributeValue(
								null, "publishingHouse");
						String bookType = xmlPull.getAttributeValue(null,
								"type");
						String price = xmlPull.getAttributeValue(null, "price");// 通过属性名来获取属性值
						String linkmanName = xmlPull.getAttributeValue(null,
								"linkmanName");
						long linkmanNumber = Long.parseLong(xmlPull
								.getAttributeValue(null, "linkmanNumber"));
						String description = xmlPull.nextText();
						BigDecimal bookPrice = new BigDecimal(price);
						// 当处于某个元素时可以调用XmlPullParser的getAttributte()方法来获取属性的值，
						// 也可调用它的nextText()获取本节点的值
						bookItem.setName(name);
						bookItem.setIcon(Drawable.createFromPath(imgPath));
						bookItem.setDescription(description);
						bookItem.setState(state);
						bookItem.setPublishingHouse(publishingHouse);
						bookItem.setType(bookType);
						bookItem.setPrice(bookPrice);
						bookItem.setLinkmanName(linkmanName);
						bookItem.setLinkmanNumber(linkmanNumber);
						list.add(bookItem);
					}
					break;
				default:
					break;
				}
				type = xmlPull.next();
			}
			in.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return list;
	}
	
	public boolean insertBooksData(BookItem bookItem){
		String xmlPath = SystemConstants.CACHE_BOOKS_DATA_XML_PATH;
		
		DocumentBuilderFactory docFactory  = DocumentBuilderFactory.newInstance();
		try{
			DocumentBuilder documentBuilder = docFactory.newDocumentBuilder();
			Document doc = documentBuilder.parse(new File(xmlPath));
			Element rootElement = doc.getDocumentElement();
			Element element = doc.createElement("book");
			element.setAttribute("id", "0000");
			element.setAttribute( "name", bookItem.getName());
			element.setAttribute("uri", "");//图片路径
			element.setAttribute("state", String.valueOf(bookItem.getState()));
			element.setAttribute("publishingHouse", bookItem.getPublishingHouse());
			element.setAttribute("type", bookItem.getType());
			element.setAttribute("price", String.valueOf(bookItem.getPrice()));
			element.setAttribute("linkmanName", bookItem.getLinkmanName());
			element.setAttribute("linkmanNumber", String.valueOf(bookItem.getLinkmanNumber()));
			element.appendChild(doc.createTextNode(bookItem.getDescription()));
			rootElement.appendChild(element);
			
			TransformerFactory tsF = TransformerFactory.newInstance();
			Transformer ts = tsF.newTransformer();
			ts.setOutputProperty(OutputKeys.ENCODING, "UTF-8");  
			ts.setOutputProperty(OutputKeys.INDENT, "  "); 
			DOMSource ds = new DOMSource(doc);
			StreamResult sr = new StreamResult(new File(xmlPath));
			
			ts.transform(ds, sr);
			
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return false;
		}	
		return true;
	}
	public boolean writeDataToXml(){
		XmlSerializer xs = Xml.newSerializer();
		File file = new File(SystemConstants.CACHE_BOOKS_DATA_XML_PATH);
		
		try{
			FileOutputStream outPutStream = new FileOutputStream(file,true); 
			xs.setOutput(outPutStream,"UTF-8");
			xs.startDocument("UTF-8", true);
			xs.startTag("", "books");
			
			/*xs.startTag("", "book");
			xs.attribute("", "id", "014444");
			xs.attribute("", "name", "百度444");
			xs.text("ggggggg");
			xs.endTag("", "book");*/
			
			xs.endTag("", "books");
			xs.endDocument();
			
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return false;
		}
		return true;
	}
}

